import React, { Component } from "react";
import PubSub from "pubsub-js"

export default class Search extends Component {

  //搜索
  handleSearch =  async() => {
    const {keywordElement:{value:keyword}} = this;
    //发布消息 兄弟组件通信
    PubSub.publish('search', {isFirst: false, isLoading: true})
    let url = `/api/search/users?q=${keyword}`
    //使用fetch方式发送请求
    // fetch(url).then(
    //   response =>{
    //     console.log("服务器链接成功！");
    //     return response.json()
    //   },
    //   error => {
    //     console.log("服务器链接失败！");
    //     return new Promise(() => {})
    //   }
    // ).then(
    //   response => {console.log("获取数据成功========》", response)},
    //   error => {console.log("获取数据失败========》", error)},
    // )

    //使用fetch方式发送请求
    try {
      const response = await fetch(url);
      const res = await response.json();
      console.log("获取的数据为：========》", res);
      PubSub.publish('search', { isLoading: false, users: res.items})
    } catch (error) {
      console.log("请求出错了");
      PubSub.publish('search', { isLoading: false, users: [], err: error})
    }
  }

  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索github 用户</h3>
        <div>
          <input ref={(c) => this.keywordElement = c} type="text" placeholder="请输入关键词" />
          <button onClick={this.handleSearch}>搜索</button>
        </div>
      </section>
    );
  }
}
